#include "qdataviewdialog.h"

#include "../libs/core/history_database/qhistorydatabaseview.h"
#include "../libs/core/qactiontoolbar.h"

#include <QVBoxLayout>
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>

QDataViewDialog::QDataViewDialog(QWidget *parent):
    QBaseDialog(parent),
    m_data_view(new QHistoryDatabaseView)
{
    QVBoxLayout *v=new QVBoxLayout;
    v->setMargin(0);
    v->setSpacing(0);
    v->addWidget(m_data_view);

    this->setLayout(v);


    this->resize(1000,600);

    QActionToolBar *tool=new QActionToolBar;

    QAction* ac;
    QList<QAction*> list;

    ac=new QAction(this);
    ac->setText(tr("Open"));
    ac->setIcon(QIcon(":/images/textfile.png"));
    connect(ac,SIGNAL(triggered()),this,SLOT(open()));
    list.append(ac);

    ac=new QAction(this);
    ac->setText(tr("Save As"));
    ac->setIcon(QIcon(":/images/save.png"));
    ac->setEnabled(false);
    connect(ac,SIGNAL(triggered()),this,SLOT(save()));
    connect(m_data_view,SIGNAL(has_data(bool)),ac,SLOT(setEnabled(bool)));
    list.append(ac);

    ac=new QAction(this);
    ac->setText(tr("Clear"));
    ac->setIcon(QIcon(":/images/clear.png"));
    connect(ac,SIGNAL(triggered()),m_data_view,SLOT(clear()));
    list.append(ac);

    ac=new QAction(this);
    ac->setSeparator(true);
    list.append(ac);


    tool->addButtonActions(list);
    m_data_view->set_toolbar(tool);
}

void QDataViewDialog::open()
{
    QString str=QFileDialog::getOpenFileName(this,tr("Open"),QDir::currentPath(),tr("DB File(*.db)"));
    if(str!="")
    {
        if(!m_data_view->load(str))
        {
            QMessageBox::critical(this,tr("Warning"),tr("Load Failed!"));
            m_file_name="";
        }
        else
        {
            m_file_name=str;
        }
    }
}

void QDataViewDialog::save()
{
    if(m_file_name=="")
    {
        return;
    }
    QString str=QFileDialog::getSaveFileName(this,tr("Save"),QDir::currentPath(),tr("DB File(*.db)"));
    if(str!="" && str!=m_file_name)
    {
        QFile f(str);

        if(!f.open(QFile::ReadWrite))
        {
            QMessageBox::critical(this,tr("Warning"),tr("Save Failed!"));
            return;
        }
        else
        {
            f.resize(0);
            QFile ff(m_file_name);
            if(!ff.open(QFile::ReadOnly))
            {
                QMessageBox::critical(this,tr("Warning"),tr("Save Failed!"));
                return;
            }
            f.write(ff.readAll());
            f.close();
            ff.close();
        }
    }
}
